﻿using System.Collections.Generic;
using LitJson;
using UnityEngine;

namespace Config
{
	public abstract class SConfigItem
	{
		public string id;
		
		public abstract void Init(JsonData data);
	}
    public static class SConfigFinder<T> where T : SConfigItem, IJsonFile, new()
    {
        /// <summary>
        /// 获取配置列表
        /// </summary>
        public static List<T> List
        {
            get
            {
                if (!s_loaded) Initialize();
                return s_list;
            }
        }
        private static List<T> s_list;
        /// <summary>
        /// 获取配置字典
        /// </summary>
        public static Dictionary<string, T> Dict
        {
            get
            {
                if (!s_loaded) Initialize();
                return s_dict;
            }
        }
        private static Dictionary<string, T> s_dict;
        
        private static bool s_loaded;
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initialize()
        {
            if (s_loaded) return;
            var jsonData = LitJson.JsonMapper.ToObject(ConfigUtility.LoadConfigText<T>());
            var count = jsonData.Count;
            s_list = new List<T>(count);
            s_dict = new Dictionary<string, T>(count);
            for (int i = 0; i < count; i++)
            {
                var data = jsonData[i];
                var t = new T();
                t.Init(data);
                s_list.Add(t);
                s_dict.Add(t.id, t);
            }
            s_loaded = true;
        }
        
        /// <summary>
        /// 寻找配置
        /// </summary>
        public static T Find(string id)
        {
            if (!s_loaded) Initialize();
            if (s_dict.TryGetValue(id, out var t))
            {
                return t;
            }
            throw new KeyNotFoundException($"表中不存在key: {id}");
        }
    }
}
